import {watch} from "vue";
import {defineStore} from 'pinia';
import type {RouteRecordRaw} from 'vue-router';

import {adminMenu} from '@/config/MenuConfig';
import type {MenuMo} from '@/service/entity/MenuMo';
import {removeAdminToken} from '@/utils/setToken';

export const layoutStore = defineStore('layoutStore', () => {
    const pageTitle = ref('')

    const updatePageTitle = (val) => {
        pageTitle.value = val
    }

    const currentPath = ref('')

    const updateCurrentPath = (val) => {
        console.log("currentPath ==>>",val)
        currentPath.value = val
    }

    watch(pageTitle, () => {
        console.log('-----------------', pageTitle.value)
    })

    let menuData = reactive<MenuMo[]>([])
    let collapse = ref(false)
    let ImportPath = import.meta.glob('@/views/**/*.vue')

    function getMenu() {
        return menuData
    }

    function changeCollapse() {
        collapse.value = !collapse.value
    }

    function getStailData() {
        menuData = adminMenu
    }

    function getRoutesData(menuData: MenuMo[], parantFilePath = '') {
        let addPath = ''
        parantFilePath === '' ? addPath = '' : addPath = parantFilePath + '/'
        let arr: RouteRecordRaw[] = []
        menuData.forEach(item => {
            if (item?.children?.length) {
                getRoutesData(item.children, parantFilePath + item.FileUrl)
            } else {
                arr.push({
                    path: item.pathUrl,
                    name: item.pathUrl,
                    component: ImportPath['/src/views/' + parantFilePath + item.FileUrl + '.vue'],
                    meta: {
                        title: item.label
                    }
                })
            }
        });
        return arr
    }

    //获取转换完的router
    function getRouter() {
        getStailData()
        return getRoutesData(menuData)
    }

    return {
        currentPath,
        updateCurrentPath,
        pageTitle,
        getRouter,
        getMenu,
        changeCollapse,
        menuData,
        collapse,
        updatePageTitle
    }
})